<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head th:replace="main :: common_head">
</head>
<style>
    .table td {
        margin: 0;
        padding: 0;
    }
    .copy-price {
        display: flex;
    }
    .form-actions > button {
        margin: 0 5px;
    }
    #app {
        margin-right: 65px;
    }
    [v-cloak] {
        display: none;
    }
</style>
<body>

<div class="container-fluid-full">
    <div class="row-fluid">

        <noscript>
            <div class="alert alert-block span10">
                <h4 class="alert-heading">Warning!</h4>
                <p>You need to have <a href="" target="_blank">JavaScript</a> enabled to use this site.</p>
            </div>
        </noscript>

        <!-- start: Content -->
        <div id = "app">
            <div id="content" class="span10" style="width: 100%">
                <ul class="breadcrumb" th:if="${#request.getParameter('breadcrumb') == 'true'}">
                    <li>
                        <i class="fas fa-circle-notch"></i>
                        <a id="home" href="#" onclick="parent.location.reload()">主页</a>
                        <i class="icon-angle-right"></i>
                    </li>
                    <li><a href="#">[[${deviceName}]]电价修改</a></li>
                </ul>
                <div class="row-fluid sortable">
                    <div class="box span12">
                        <div class="box-header" data-original-title>
                            <!--                        <h2><i class="halflings-icon white edit"></i><span class="break"></span>[[${deviceName}]]</h2>-->
                            <h2 v-cloak><i class="halflings-icon white edit"></i><span class="break"></span>{{graphName}}</h2>
                        </div>
                        <div class="box-content" style="position:relative">
                            <form class="form-horizontal"
                                  th:action="@{/electricity/updateElePrice/{graphId}(graphId=${graphId})}" method="post">
                                <fieldset id="price-container">
                                    <div style="display: flex;justify-content: space-evenly">
                                        <div style="width: 620px" id="eleEdit">
                                            <div style="display: none" id="mock"></div>
                                            <div class="control-group" th:each="price:${prices}">
                                                <label class="control-label" style="width: 100px;margin-left: 20px">
                                                    <span class="input-group clockpicker">
                                                        <input name="startTimeList" style="width: 100px;" type="text"
                                                               class="form-control start-time" th:value="${price.startTime}">
                                                        <span class="input-group-addon">
                                                            <span class="glyphicon glyphicon-time"></span>
                                                        </span>
                                                    </span>
                                                </label>
                                                <span style="position: relative;float: left;left: 25px;top: 10px;font-size: 20px;">~</span>
                                                <label class="control-label" style="width: 100px;margin-left: 35px">
                                                    <span class="input-group clockpicker">
                                                        <input name="endTimeList" style="width: 100px;" type="text"
                                                               class="form-control end-time" th:value="${price.endTime}">
                                                        <span class="input-group-addon">
                                                            <span class="glyphicon glyphicon-time"></span>
                                                        </span>
                                                    </span>
                                                </label>


                                                <div class="controls form-inline" style="padding-top: 5px;">
                                                    <input style="margin-left: 60px;width: 135px" class="input-xlarge focused price"
                                                           type="number" placeholder=""
                                                           name="priceList" th:value="${price.price}" min="0.0000" step="0.0001">
                                                    <input name="idList" class="idx" style="display: none" th:value="${price.id}">

                                                    <!-- 删除按钮 -->
                                                    <button style="margin-left: 10px;" type="button" class="btn btn-small btn-danger del-item">删除</button>
                                                </div>
                                            </div>
                                        </div>

                                        <div id="notice" style="margin: 0 50px 50px 50px">
                                            提示:<br><br>
                                            峰段（电价最高的时间段)<br><br>
                                            谷段（电价最低的时间段）<br><br>
                                            平段（剩余电价的时间段)<br><br>
                                        </div>
                                    </div>
                                    <div class="form-actions" style="display: flex;">
                                        <div  class="copy-price">
                                            <div style="
                                        text-align: center;
                                        height: 35px;
                                        line-height: 35px;
                                        background: white;
                                        padding: 0 20px;
                                        ">从以下图谱复制电价</div>
                                            <div style="background: white;
                                            margin: 0 10px;
                                            height: 35px;">
                                                <ul id="mytab" class="nav nav-pills nav-justified">
                                                    <li role="presentation" class="dropdown" id="myli" v-cloak>
                                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                                            {{initGraph.graphName}}
                                                            <span class="caret"></span>
                                                        </a>
                                                        <ul class="dropdown-menu">
                                                            <li v-for="graph in graphInfos">
                                                                <a v-on:click="setSelectedData(graph)">{{graph.graphName}}</a>
                                                            </li>
                                                        </ul>
                                                    </li>
                                                </ul>
                                            </div>
                                            <button type="button" class="btn btn-primary" v-on:click="getPriceByGraphId">确定</button>
                                        </div>

                                        <button type="button" class="btn btn-primary" onclick="addItem()">新增</button>
                                        <button type="submit" class="btn btn-primary">提交</button>
                                        <button type="button" class="btn btn-primary" onclick="toElePrice()">返回</button>
                                        <button id="reset" style="float: right;" type="button" class="btn btn-warning">重置</button>
                                    </div>
                                </fieldset>
                            </form>
                        </div>
                    </div><!--/span-->
                </div><!--/row-->
            </div>
        </div>

    </div>
</div>

<div class="modal hide fade" id="myModal">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h3>Settings</h3>
    </div>
    <div class="modal-body">
        <p>Here settings can be configured...</p>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal">Close</a>
        <a href="#" class="btn btn-primary">Save changes</a>
    </div>
</div>
<div class="common-modal modal fade" id="common-Modal1" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-content">
        <ul class="list-inline item-details">
            <li><a href="http://sc.chinaz.com">Admin templates</a></li>
            <li><a href="http://sc.chinaz.com">Bootstrap themes</a></li>
        </ul>
    </div>
</div>
<div class="clearfix"></div>

<div th:replace="main::common_js" ></div>

<script th:inline="javascript" th:src="@{/js/vue.min.js}"></script>
<script th:src="@{/js/tools.js}"></script>
<script th:inline="javascript">
    //<![CDATA[
    let getNumParam = val=>{return isNumber(val)?val:""}
    var vm = new Vue({
        el: '#app',
        created: function () {
            if (isNumber(getPathParamAferSlashLast())) {
                this.graphId = getPathParamAferSlashLast()
            }
            that = this
            $.ajax({
                type: "GET",
                url: "/multipower/electricity/viewGraphInfo",
                dataType: "json",
                async: true,
                success: function (data) {
                    // 过滤当前图谱信息，同时保存图谱名称
                    that.graphInfos = data.allGraphInfo.filter(
                        function(item) {
                            if (item.graphId == that.graphId ) {
                                that.graphName = item.graphName
                                return false;
                            }
                            return true;
                        }
                    )
                    console.log(that.graphInfos,that.graphName)
                }
            })
        },
        data: {
            graphId:"",
            graphName:"",
            initGraph: {
                "graphName":"请选择图谱"
            },
            graphInfos: [],
        },
        methods: {
            setSelectedData: function(data) {
                that.initGraph = data
            },
            getPriceByGraphId: function () {
                that = this
                let data = that.initGraph
                $.ajax({
                    type: "POST",
                    url: "/multipower/electricity/autoUpdateEleType/" + data.graphId,
                    dataType: "json",
                    async: false,
                    success: function () {

                    }
                })
                $.ajax({
                    type: "GET",
                    url: "/multipower/electricity/viewPriceByGraphId/" + data.graphId,
                    dataType: "json",
                    async: true,
                    success: function (data) {
                        // 首先清空
                        $('.control-group').remove()
                        if (data.msg == undefined) {
                            data.prices.forEach(item => {
                                addItem(item.startTime, item.endTime, item.price, item.id)
                            })
                        }
                    }
                })
            }
        }
    })
    //]]>
    console.log(vm)
</script>
<script th:inline="javascript">
    breadcrumb()
    window.onload = function() {
        parent.modifyTitle('电价管理')
    }
</script>

<script th:src="@{/js/detect-element-resize.js}"></script>
<script th:src="@{/js/iframe-resize.js}"></script>

<script type="text/javascript" th:inline="javascript">
    $('.clockpicker').clockpicker({placement: 'bottom', align: 'left', donetext: '选择'});
    $(".del-item").click(function () {
        $(this).parents(".control-group").remove()
    })

</script>
<script th:inline="javascript">
    $("#reset").click(function () {
        // 改变重置逻辑，直接刷新该页面
        location.reload()
    })

    $(".form-horizontal").submit(function (e) {
        var startTimeList = []
        var endTimeList = []
        var priceList = []
        var idList = []
        var prices = []

        $(".control-group").each(function () {
            var startTime = $(this).find(".control-label .start-time").val()
            var endTime = $(this).find(".control-label .end-time").val()
            var price = $(this).find(".controls .price").val()
            var id = $(this).find(".controls .idx").val()
            startTimeList.push(startTime)
            endTimeList.push(endTime)
            price = Math.round(parseFloat(price)*10000)/10000;
            priceList.push(price)
            if (id != undefined && id != "") {
                idList.push(id)
            }
            if (prices.indexOf(price) == -1) {
                prices.push(price)
            }
        })

        // 如果没有提供峰谷平三种价格，则不允许提交(防止策略生成时出现问题)
        if (prices.length != 3) {
            layer.msg("必须提供且只能提供峰、谷、平三种价格")
            return false
        }

        // 处理一下时间格式
        startTimeList = startTimeList.map(function (item) {
            var temp = item.split(":")
            var hour = parseInt(temp[0])
            var minute = parseInt(temp[1]) / 60
            return hour + minute
        })
        endTimeList = endTimeList.map(function (item) {
            var temp = item.split(":")
            var hour = parseInt(temp[0])
            var minute = parseInt(temp[1]) / 60
            return hour + minute
        })

        // 起始时间不能等于结束时间
        for (var i=0;i<startTimeList.length;i++) {
            if (startTimeList[i] == endTimeList[i]) {
                layer.msg("起始时间不能等于结束时间")
                return false
            }
        }

        // 1. 原则上所有startTimeList中的时间都应该在endTimeList中找得到，这样时间才是一个闭环
        var tempStartTimeList = startTimeList.slice(0).sort()
        var tempEndTimeList = endTimeList.slice(0).sort()
        if (tempStartTimeList.toString() != tempEndTimeList.toString()) {
            layer.msg("时间段未闭合")
            return false
        }

        // 2. 原则上不允许出现时间段重复的现象
        for (var i = 0; i < startTimeList.length; i++) {
            var s = startTimeList[i]
            var e = endTimeList[i]

            for (var j = 0; j < startTimeList.length; j++) {
                if (i != j && s < endTimeList[j] && e > startTimeList[j]) {
                    layer.msg("时间段重复")
                    return false;
                }
            }
        }

        var form = $(".form-horizontal")
        // 删除了的记录的id
        var list = [[${prices}]]
        var delList = []
        list.forEach(function (item) {
            if (idList.indexOf(item.id.toString()) == -1) {
                delList.push(item.id.toString())
            }
        })
        if (delList.length > 0) {
            var addDom = $("<input type='hidden' name='idDeleteList' />")
            addDom.attr("value", delList)
            form.append(addDom)
        }
        return true
    })
</script>
<script th:inline="javascript">
    //返回上一页
    function toElePrice() {
        let graphId = getPathParamAferSlashLast()
        if (isNumber(graphId)) {
            window.location.href = "/multipower/electricity/back/" + graphId
        } else {
            window.history.back(-1)
        }
    }

    // 新增时间段+价格
    function addItem(startTime, endTime, price, id) {
        var dom = $("#eleEdit .control-group:last")
        if ($("#price-container .control-group:last").length == 0) {
            dom = $("#price-container #mock")
        }
        if (startTime == undefined) {
            startTime = '00:00'
        }
        if (endTime == undefined) {
            endTime = '00:00'
        }
        if (price == undefined) {
            price = '0.0000'
        }
        if (id != undefined) {
            dom.after("<div class=\"control-group\"><label class=\"control-label\" style=\"width: 100px;margin-left: 20px\">" +
                "<span class=\"input-group clockpicker\"><input name=\"startTimeAddList\" style=\"width: 100px;\" type=\"text\" class=\"form-control start-time\" value=\"" + startTime + "\">" +
                "<span class=\"input-group-addon\"><span class=\"glyphicon glyphicon-time\"></span></span></span></label>" +
                "<span style=\"position: relative;float: left;left: 25px;top: 10px;font-size: 20px;\">~</span>" +
                "<label class=\"control-label\" style=\"width: 100px;margin-left: 35px\"><span class=\"input-group clockpicker\">" +
                "<input name='endTimeAddList' style=\"width: 100px;\" type=\"text\" class=\"form-control end-time\" value=\"" + endTime + "\"><span class=\"input-group-addon\">" +
                "<span class=\"glyphicon glyphicon-time\"></span></span></span></label><div class=\"controls form-inline\" style=\"padding-top: 5px;\">" +
                "<input style=\"margin-left: 60px;width: 135px\" class=\"input-xlarge focused price\" type=\"number\" placeholder=\"\"name=\"priceAddList\" value=\"" + price + "\" min=\"0.0000\" step=\"0.0001\">" +
                "<input name='idList' class=\"idx\" style=\"display: none\" value=\"" + id + "\"><button style=\"margin-left: 15px;\" type=\"button\" class=\"btn btn-small btn-danger del-item\">删除</button></div></div>")
        } else {
            dom.after("<div class=\"control-group\"><label class=\"control-label\" style=\"width: 100px;margin-left: 20px\">" +
                "<span class=\"input-group clockpicker\"><input name=\"startTimeAddList\" style=\"width: 100px;\" type=\"text\" class=\"form-control start-time\" value=\"" + startTime + "\">" +
                "<span class=\"input-group-addon\"><span class=\"glyphicon glyphicon-time\"></span></span></span></label>" +
                "<span style=\"position: relative;float: left;left: 25px;top: 10px;font-size: 20px;\">~</span>" +
                "<label class=\"control-label\" style=\"width: 100px;margin-left: 35px\"><span class=\"input-group clockpicker\">" +
                "<input name='endTimeAddList' style=\"width: 100px;\" type=\"text\" class=\"form-control end-time\" value=\"" + endTime + "\"><span class=\"input-group-addon\">" +
                "<span class=\"glyphicon glyphicon-time\"></span></span></span></label><div class=\"controls form-inline\" style=\"padding-top: 5px;\">" +
                "<input style=\"margin-left: 60px;width: 135px\" class=\"input-xlarge focused price\" type=\"number\" placeholder=\"\"name=\"priceAddList\" value=\"" + price + "\" min=\"0.0000\" step=\"0.0001\">" +
                "<input class=\"idx\" style=\"display: none\" value=\"\"><button style=\"margin-left: 15px;\" type=\"button\" class=\"btn btn-small btn-danger del-item\">删除</button></div></div>")
        }

        $(".clockpicker").clockpicker({
            placement: 'bottom', align: 'left', donetext: '选择'
        })

        $(".del-item").click(function () {
            $(this).parents(".control-group").remove()
        })
    }
</script>


</body>
</html>
